<template>
  <div class="main">
    <a-form-model class="user-layout-login" @keyup.enter.native="handleSubmit">
      <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"  @change="handleTabClick">
        <a-tab-pane key="tab1" tab="管理员登录">
          <login-account ref="alogin" @validateFail="validateFail" @success="requestSuccess" @fail="requestFailed"></login-account>
        </a-tab-pane>

        <a-tab-pane key="tab2" tab="员工登录">
          <login-account ref="elogin" :isEmployee="true" @validateFail="validateFail" @success="requestSuccess" @fail="requestFailed"></login-account>
        </a-tab-pane>
      </a-tabs>

      <a-form-model-item>
        <a-checkbox @change="handleRememberMeChange" default-checked>自动登录</a-checkbox>
        <router-link :to="{ name: 'alteration'}" class="forge-password" style="float: right;">
          忘记密码
        </router-link>
      </a-form-model-item>

      <a-form-item style="margin-top:24px">
        <a-button size="large"  type="primary"  htmlType="submit"  class="login-button"  :loading="loginBtn"  @click.stop.prevent="handleSubmit" :disabled="loginBtn">确定
        </a-button>
      </a-form-item>

    </a-form-model>

    <two-step-captcha v-if="requiredTwoStepCaptcha" :visible="stepCaptchaVisible" @success="stepCaptchaSuccess" @cancel="stepCaptchaCancel"></two-step-captcha>
    <login-select-tenant ref="loginSelect" @success="loginSelectOk"></login-select-tenant>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, ENCRYPTED_STRING } from '@/store/mutation-types'
import LoginSelectTenant from './LoginSelectTenant'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { getEncryptedString } from '@/utils/encryption/aesEncrypt'
import { timeFix } from '@/utils/util'

import LoginAccount from './LoginAccount'

export default {
    components: {
      LoginSelectTenant,
      TwoStepCaptcha,
      LoginAccount
    },
    data () {
      return {
        customActiveKey: 'tab1',
        rememberMe: true,
        loginBtn: false,
        requiredTwoStepCaptcha: false,
        stepCaptchaVisible: false,
        encryptedString:{
          key:"",
          iv:"",
        },
      }
    },
    created() {
      // 只有在非登录状态下才清除token
      if (!Vue.ls.get(ACCESS_TOKEN)) {
        Vue.ls.remove(ACCESS_TOKEN)
      }
      this.getRouterData();
      this.rememberMe = true
    },
    methods:{
      handleTabClick(key){
        this.customActiveKey = key
      },
      handleRememberMeChange(e){
        this.rememberMe = e.target.checked
      },
      /**跳转到登录页面的参数-账号获取*/
      getRouterData(){
        this.$nextTick(() => {
          let temp = this.$route.params.username || this.$route.query.username || ''
          if (temp) {
            this.$refs.alogin.acceptUsername(temp)
          }
        })
      },

      //登录
      handleSubmit () {
        this.loginBtn = true;
        if (this.customActiveKey === 'tab1') {
          // 使用管理员账户密码登录
          this.$refs.alogin.handleLogin(this.rememberMe)
        } else {
          //使用员工账户密码登录
          this.$refs.elogin.handleLogin(this.rememberMe)
        }
      },
      // 校验失败
      validateFail(){
        this.loginBtn = false;
      },
      // 登录后台成功
      requestSuccess(loginResult){
        // 判断是否是员工登录
        if (this.customActiveKey === 'tab2') {
          // 确保token已经保存到localStorage
          if (loginResult && loginResult.token) {
            // 再次确认token已保存
            Vue.ls.set(ACCESS_TOKEN, loginResult.token, 7 * 24 * 60 * 60 * 1000)
            console.log('员工登录成功，token已保存:', loginResult.token)
          }
          this.loginSuccess()
        } else {
          // 管理员登录需要选择租户
          this.$refs.loginSelect.show(loginResult)
        }
      },
      //登录后台失败
      requestFailed (err) {
        let description = ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试"
        this.$notification[ 'error' ]({
          message: '登录失败',
          description: description,
          duration: 4,
        });
        //账户密码登录错误后更新验证码
        if(this.customActiveKey === 'tab1'){
          this.$refs.alogin.handleChangeCheckCode()
        } else {
          this.$refs.elogin.handleChangeCheckCode()
        }
        this.loginBtn = false;
      },
      loginSelectOk(){
        this.loginSuccess()
      },
      //登录成功
      loginSuccess () {
        // 更新路由
        console.log('开始获取权限菜单...');
        
        this.$store.dispatch('GetPermissionList').then((res) => {
          console.log('获取权限菜单成功:', res);
          
          // 输出当前用户的按钮权限
          const buttonAuth = JSON.parse(sessionStorage.getItem('SYS_BUTTON_AUTH') || '[]');
          console.log('当前用户的按钮权限:', buttonAuth);
          
          // 过滤出类型为2的按钮权限（按钮类型）
          const buttonPermissions = buttonAuth.filter(item => item.type === '2');
          console.log('按钮类型权限:', buttonPermissions);
          
          // 输出用户权限（USER_AUTH）
          const userAuth = JSON.parse(sessionStorage.getItem('LOGIN_USER_BUTTON_AUTH') || '[]');
          console.log('用户权限(USER_AUTH):', userAuth);
          
          // 输出菜单权限
          console.log('菜单权限(permissionList):', this.$store.state.user.permissionList);
          
          // 按权限类型统计
          const authStats = {
            button: buttonPermissions.length,
            menu: this.$store.state.user.permissionList.length,
            userAuth: userAuth.length
          };
          console.log('权限统计:', authStats);
          
          // 权限加载完成后再跳转
          this.$router.push({ path: "/dashboard/analysis" }).then(() => {
            console.log('路由跳转成功，准备刷新页面...');
            // 延迟500ms后刷新页面，确保路由已完全加载
            setTimeout(() => {
              console.log('执行页面刷新');
              window.location.reload();
            }, 500);
          }).catch((err)=>{
            console.log('登录跳转首页出错:', err);
          })
          
          this.$notification.success({
            message: '欢迎',
            description: `${timeFix()}，欢迎回来`,
          });
        }).catch((error) => {
          console.error('获取权限菜单失败:', error);
          this.$notification.error({
            message: '系统提示',
            description: '获取菜单权限失败，请重新登录！'
          });
          // 登出处理
          this.$store.dispatch('Logout').then(() => {
            this.loginBtn = false;
          });
        })
      },

      stepCaptchaSuccess () {
        this.loginSuccess()
      },
      stepCaptchaCancel () {
        this.Logout().then(() => {
          this.loginBtn = false
          this.stepCaptchaVisible = false
        })
      },
      //获取密码加密规则
      getEncrypte(){
        var encryptedString = Vue.ls.get(ENCRYPTED_STRING);
        if(encryptedString == null){
          getEncryptedString().then((data) => {
            this.encryptedString = data
          });
        }else{
          this.encryptedString = encryptedString;
        }
      }

    }

  }
</script>
<style lang="less" scoped>
  .user-layout-login {
    label {
      font-size: 14px;
    }
  .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

  .forge-password {
      font-size: 14px;
    }

    button.login-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 100%;
    }
  }
</style>
<style>
  .valid-error .ant-select-selection__placeholder{
    color: #f5222d;
  }
</style>